<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <TodoHeader @addList="addList" />

    <!-- 主体部分 -->
    <TodoBody
      :list="renderList"
      @delList="delList"
      @changeStatus="changeStatus"
      :isAll='isAll'
      @changeAll='changeAll'
    />

    <!-- 底部部分 -->
    <TodoFooter
      :listLength="listLength"
      @clearList="clearList"
      v-show="list.length"
      :isDoneAll="isDoneAll"
      :type="type"
      @changeType="changeType"
    ></TodoFooter>
  </section>
</template>

<script>
import TodoHeader from './components/TodoHeader.vue';
import TodoBody from './components/TodoBody.vue';
import TodoFooter from './components/TodoFooter.vue';
export default {
  components: {
    TodoHeader,
    TodoBody,
    TodoFooter,
  },
  data() {
    return {
      type: 'all',
      list: JSON.parse(localStorage.getItem('TodoList')) || [
        { id: 1, name: '吃饭', isDone: true },
        { id: 2, name: '睡觉', isDone: false },
        { id: 3, name: '打豆豆', isDone: true },
      ],
    };
  },
  methods: {
    //删除事件
    delList(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    //修改状态
    changeStatus(id) {
      const str = this.list.find((item) => item.id === id);
      str.isDone = !str.isDone;
    },
    //添加事件
    addList(value) {
      const obj = { id: +new Date(), name: value, isDone: false };
      this.list = [obj, ...this.list];
    },
    //清除已完成的
    clearList() {
      this.list = this.list.filter((item) => !item.isDone);
    },
    //切换 修改父组件中的type
    changeType(type) {
      this.type = type;
    },

    changeAll(flag){
        this.list.forEach(item => item.isDone = flag)
    }
  },
  //计算属性 剩余
  computed: {
    listLength() {
      return this.list.filter((item) => !item.isDone).length;
    },
    //清除已完成
    isDoneAll() {
      // 有 只要有一个true就显示
      return this.list.some((item) => item.isDone);
    },
    //   在body里父传子:list="renderList"
    renderList() {
      switch (this.type) {
        case 'all':
          return this.list;
        case 'active':
          return this.list.filter((item) => !item.isDone);
        case 'completed':
          return this.list.filter((item) => item.isDone);
        default:
          return this.list;
      }
    },
   //全选反选
    isAll() {
      return this.list.every((item) => item.isDone);
    },
  },
  watch: {
    //数据存本地
    list: {
      deep: true,
      immediate: true,
      handler(value) {
        localStorage.setItem('TodoList', JSON.stringify(value));
      },
    },
  },
};
</script>

<style></style>
